//
//  DeviceScanViewController.m
//  sentorise
//
//  Created by admin on 2025/8/25.
//

#import "DeviceScanViewController.h"
#import "DeviceScanResultViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <Photos/Photos.h>
#import "GlobalDefine.h"
#import "DeviceScanResultViewController.h"
#import "DeviceConnectCheckView.h"
#import "ProgressHUD.h"
#import "LookDataViewController.h"
#import "DeviceScanResultViewController.h"
#import "HelpCenterViewController.h"

@interface QROverlayView : UIView

@property (nonatomic, assign) CGRect scanRect;

@end

@interface DeviceScanViewController ()<AVCaptureMetadataOutputObjectsDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, strong) AVCaptureSession *session;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;
@property (nonatomic, strong) AVCaptureMetadataOutput *metadataOutput;
@property (nonatomic, strong) QROverlayView *overlay;
@property (nonatomic, strong) UIButton *flashBtn;
@property (nonatomic, strong) UIView *scanResultView;
@property (nonatomic, strong) UILabel *scanResultLabel;
@property (nonatomic, strong) UIView *lightView;

@property (nonatomic, strong) NSString *resultCode;
@property (nonatomic, assign) CGRect scanRect;

@end

@implementation DeviceScanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blackColor];
    
    [[BTManager sharedBTManager] retartScan];

    CGFloat w = 260;
    CGFloat top = StatusBarHeight + 44 + 70 + 40;
    self.scanRect = CGRectMake((kWidth - w)/2, top, w, w);

    [self setupCamera];
    [self buildUI];
    
//    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(kWidth-100, StatusBarHeight + 40, 100, 40)];
//    [btn setTitle:@"查看" forState:UIControlStateNormal];
//    [btn addTarget:self action:@selector(look) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:btn];
}

- (void)restartView {
    [self actionHide];
}

- (void)look {
    LookDataViewController *vc = [[LookDataViewController alloc] initWithNibName:@"LookDataViewController" bundle:nil];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 摄像头 & 识别
- (void)setupCamera {
    // 1. 获取摄像头设备
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    NSError *error = nil;
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
    if (!input) {
        NSLog(@"摄像头不可用: %@", error.localizedDescription);
        return;
    }

    // 2. 创建会话
    self.session = [[AVCaptureSession alloc] init];
    if ([self.session canAddInput:input]) {
        [self.session addInput:input];
    }

    // 3. 输出对象
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
    if ([self.session canAddOutput:output]) {
        [self.session addOutput:output];
    }

    // 设置代理
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode]; // 只识别二维码

    // 4. 预览图层
    self.previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
    self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    self.previewLayer.frame = CGRectMake(0, 0, kWidth, kHeight - 60 - 80 - 20 - 10);
    [self.view.layer addSublayer:self.previewLayer];

    // 5. 设置扫描框区域（注意坐标是相对比例，y 在前 x 在后）
    CGRect screenRect = [UIScreen mainScreen].bounds;
    CGRect scanRect = self.scanRect;

    CGFloat x = scanRect.origin.y / screenRect.size.height;
    CGFloat y = scanRect.origin.x / screenRect.size.width;
    CGFloat height = scanRect.size.height / screenRect.size.height;
    CGFloat width = scanRect.size.width / screenRect.size.width;

    output.rectOfInterest = CGRectMake(x, y, height, width);

    // 6. 开始运行
    [self.session startRunning];
}

- (void)actionBack {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)actionHelp {
    HelpCenterViewController *vc = [[HelpCenterViewController alloc] initWithNibName:@"HelpCenterViewController" bundle:nil];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)actionInput {
    DeviceScanResultViewController *vc = [[DeviceScanResultViewController alloc] initWithNibName:@"DeviceScanResultViewController" bundle:nil];
    WeakSelf
    vc.inputDown = ^(NSString *code) {
        weakSelf.resultCode = code;
        weakSelf.scanResultView.hidden = NO;
        weakSelf.scanResultLabel.text = code;
    };
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)actionHide {
    self.scanResultView.hidden = YES;
    self.scanResultLabel.text = @"";
    self.resultCode = @"";
    [self refreshSession];
}

- (void)actionConfirm {
    BOOL isExtence = NO;
    CBPeripheral *peripheral = nil;
    NSString *mac = @"";
    for (NSString *key in [BTManager sharedBTManager].advertisementDataDict.allKeys) {
        NSDictionary *dict = [[BTManager sharedBTManager].advertisementDataDict objectForKey:key] ?: @{};
        NSData *data = [dict objectForKey:@"kCBAdvDataManufacturerData"];
        Byte *receieveData = (Byte*)data.bytes;
        NSMutableArray *macs = [NSMutableArray array];
        for (NSInteger i=data.length-4; i>=0; i--) {
            [macs addObject:[NSString stringWithFormat:@"%02X", receieveData[i]]];
            if (macs.count >= 6) {
                break;
            }
        }
        mac = [macs componentsJoinedByString:@":"];
        if ([mac isEqualToString:self.resultCode]) {
            isExtence = YES;
//            [ProgressHUD showErrorMessage:[NSString stringWithFormat:@"%@==>Mac地址匹配成功", key]];
            for (CBPeripheral *p in [BTManager sharedBTManager].peripherals) {
                if ([p.name isEqualToString:key]) {
                    peripheral = p;
                    break;
                }
            }
            break;
        }
    }
    if (!isExtence || !peripheral) {
        [ProgressHUD showErrorMessage:NSLocalizedString(@"Bluetooth matching failed, please try again", nil)];
        return;
    }

    DeviceScanResultViewController *vc = [[DeviceScanResultViewController alloc] initWithNibName:@"DeviceScanResultViewController" bundle:nil];
    vc.mac = self.resultCode;
    vc.type = 1;
    vc.peripheral = peripheral;
    [self.navigationController pushViewController:vc animated:YES];
    
    [self actionHide];
}

#pragma mark - UI
- (UIButton *)pillButtonWithTitle:(NSString *)title {
    UIButton *b = [UIButton buttonWithType:UIButtonTypeSystem];
    [b setTitle:title forState:UIControlStateNormal];
    [b setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    b.backgroundColor = [UIColor colorWithRed:0.25 green:0.85 blue:0.47 alpha:1];
    b.titleLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightSemibold];
    b.layer.cornerRadius = 18;
    b.contentEdgeInsets = UIEdgeInsetsMake(8, 12, 8, 12);
    return b;
}

- (void)buildUI {
    // 覆盖层
    self.overlay = [[QROverlayView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight)];
    self.overlay.scanRect = self.scanRect;
    [self.view addSubview:self.overlay];

    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(80, StatusBarHeight, kWidth - 160, 44)];
    titleLabel.text = NSLocalizedString(@"RV Battery", nil);
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.font = [UIFont systemFontOfSize:16];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:titleLabel];
    
    UIButton *backBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, StatusBarHeight, 44, 44)];
    [backBtn setImage:[UIImage imageNamed:@"scan_back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(actionBack) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backBtn];
    
//    UIButton *helpBtn = [[UIButton alloc] initWithFrame:CGRectMake(kWidth - 120, StatusBarHeight + 5, 104, 34)];
//    helpBtn.backgroundColor = RGB16(0x36434C);
//    helpBtn.layer.cornerRadius = 17;
//    helpBtn.layer.masksToBounds = YES;
//    [helpBtn setImage:[UIImage imageNamed:@"scan_help"] forState:UIControlStateNormal];
//    [helpBtn setTitle:@" Need help" forState:UIControlStateNormal];
//    helpBtn.titleLabel.font = [UIFont systemFontOfSize:12];
//    [helpBtn addTarget:self action:@selector(actionHelp) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:helpBtn];
    
    UILabel *tipsLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, StatusBarHeight + 44 + 70, kWidth - 40, 18)];
    tipsLabel.text = NSLocalizedString(@"Scan the QR code on the product.", nil);
    tipsLabel.textColor = [UIColor whiteColor];
    tipsLabel.font = [UIFont systemFontOfSize:13];
    tipsLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:tipsLabel];
    
    UILabel *descLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, kHeight - 70, kWidth - 40, 18)];
    descLabel.text = NSLocalizedString(@"If the identification is still not possible,", nil);
    descLabel.textColor = [UIColor whiteColor];
    descLabel.font = [UIFont systemFontOfSize:13];
    descLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:descLabel];
    
    UIButton *inputBtn = [[UIButton alloc] initWithFrame:CGRectMake(20, kHeight - 50, kWidth - 40, 24)];
    [inputBtn setTitle:NSLocalizedString(@"try entering it manually", nil) forState:UIControlStateNormal];
    inputBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [inputBtn setTitleColor:RGB16(0x68B82E) forState:UIControlStateNormal];
    [inputBtn addTarget:self action:@selector(actionInput) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:inputBtn];
    
    UIButton *cButton = [[UIButton alloc] initWithFrame:CGRectMake((kWidth - 54) / 2, kHeight - 60 - 80 - 20, 54, 80)];
    [cButton addTarget:self action:@selector(toggleTorch) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:cButton];
    
    UIButton *lButton = [[UIButton alloc] initWithFrame:CGRectMake(46, kHeight - 60 - 80 - 20, 54, 80)];
    [lButton addTarget:self action:@selector(openAlbum) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:lButton];
    
    UIButton *rButton = [[UIButton alloc] initWithFrame:CGRectMake(kWidth - 54 - 46, kHeight - 60 - 80 - 20, 54, 80)];
    [rButton addTarget:self action:@selector(refreshSession) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:rButton];
    
    NSArray *views = @[lButton, cButton, rButton];
    for (NSInteger i=0; i<views.count; i++) {
        UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 54, 54)];
        v.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.5];
        v.layer.cornerRadius = 27;
        [views[i] addSubview:v];
        v.userInteractionEnabled = NO;
        if (i == 1) {
            self.lightView = v;
        }
        
        UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(12, 12, 30, 30)];
        iv.image = [UIImage imageNamed:@[@"scan_ablum", @"scan_light", @"scan_refresh"][i]];
        [v addSubview:iv];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 60, 60, 20)];
        label.text = @[NSLocalizedString(@"Album", nil), NSLocalizedString(@"Flashlight", nil), NSLocalizedString(@"Refresh", nil)][i];
        label.textColor = [UIColor whiteColor];
        label.font = [UIFont systemFontOfSize:12];
        label.textAlignment = NSTextAlignmentCenter;
        [views[i] addSubview:label];
    }
    
    self.scanResultView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight)];
    self.scanResultView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.scanResultView];
    self.scanResultView.hidden = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionHide)];
    [self.scanResultView addGestureRecognizer:tap];
    
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake((kWidth - 204)/2, 230, 204, 204)];
    bgView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.5];
    bgView.layer.cornerRadius = 16;
    [self.scanResultView addSubview:bgView];
    
    UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(42, 42, 120, 97)];
    iv.image = [UIImage imageNamed:@"battery_icon"];
    [bgView addSubview:iv];
    
    self.scanResultLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 171, 184, 30)];
    self.scanResultLabel.textColor = [UIColor whiteColor];
    self.scanResultLabel.font = [UIFont systemFontOfSize:13];
    [bgView addSubview:self.scanResultLabel];
    
    UIButton *confirmBtn = [[UIButton alloc] initWithFrame:CGRectMake((kWidth - 170)/2, 230 + 204 + 50, 170, 48)];
    confirmBtn.backgroundColor = RGB16(0x68B82E);
    confirmBtn.layer.cornerRadius = 16;
    [confirmBtn setTitle:NSLocalizedString(@"Confirm", nil) forState:UIControlStateNormal];
    confirmBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [confirmBtn setTitleColor:RGB16(0x222222) forState:UIControlStateNormal];
    [confirmBtn addTarget:self action:@selector(actionConfirm) forControlEvents:UIControlEventTouchUpInside];
    [self.scanResultView addSubview:confirmBtn];
}

- (void)refreshSession {
    [self.session stopRunning];
    [self.session startRunning];
}

- (void)toggleTorch {
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if (![device hasTorch]) return;
    NSError *err = nil;
    if ([device lockForConfiguration:&err]) {
        device.torchMode = (device.torchMode == AVCaptureTorchModeOn) ? AVCaptureTorchModeOff : AVCaptureTorchModeOn;
        [device unlockForConfiguration];
        self.lightView.backgroundColor = device.torchMode == AVCaptureTorchModeOn ? RGB16(0x91D140) : [[UIColor whiteColor] colorWithAlphaComponent:0.5];
    }
}

- (void)openAlbum {
    PHAuthorizationStatus st = [PHPhotoLibrary authorizationStatus];
    if (st == PHAuthorizationStatusNotDetermined) {
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            dispatch_async(dispatch_get_main_queue(), ^{ [self openAlbum]; });
        }];
        return;
    }
    if (st == PHAuthorizationStatusDenied || st == PHAuthorizationStatusRestricted) return;

    UIImagePickerController *picker = [UIImagePickerController new];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark - 相册二维码识别（CoreImage）
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {
    UIImage *img = info[UIImagePickerControllerOriginalImage];
    [picker dismissViewControllerAnimated:YES completion:nil];
    if (!img) return;

    CIImage *ci = [[CIImage alloc] initWithImage:img];
    CIDetector *det = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{CIDetectorAccuracy: CIDetectorAccuracyHigh}];
    NSArray *features = [det featuresInImage:ci];
    for (CIQRCodeFeature *f in features) {
        if (f.messageString.length > 0) { [self handleResult:f.messageString]; return; }
    }
    // 无结果可提示
}

#pragma mark - 扫描回调（仅框内识别，rectOfInterest 已限制）
- (void)captureOutput:(AVCaptureOutput *)output didOutputMetadataObjects:(NSArray<__kindof AVMetadataObject *> *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    if (metadataObjects.count == 0) return;
    AVMetadataMachineReadableCodeObject *obj = (AVMetadataMachineReadableCodeObject *)metadataObjects.firstObject;
    if (![obj.type isEqualToString:AVMetadataObjectTypeQRCode]) return;
    if (obj.stringValue.length == 0) return;
    [self.session stopRunning];
    [self handleResult:obj.stringValue];
}

- (void)handleResult:(NSString *)value {
    if (self.resultCode.length) {
        return;
    }
    self.resultCode = value;
    self.scanResultView.hidden = NO;
    self.scanResultLabel.text = value;
}

@end


@implementation QROverlayView {
    CAShapeLayer *_maskLayer; // 外暗、内镂空
    CAShapeLayer *_cornerLayer; // 四角描边
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor clearColor];

        _maskLayer = [CAShapeLayer layer];
        _maskLayer.fillRule = kCAFillRuleEvenOdd;
        _maskLayer.fillColor = [[UIColor colorWithWhite:0 alpha:0.55] CGColor];
        [self.layer addSublayer:_maskLayer];

        _cornerLayer = [CAShapeLayer layer];
        _cornerLayer.strokeColor = [UIColor whiteColor].CGColor;
        _cornerLayer.fillColor = [UIColor clearColor].CGColor;
        _cornerLayer.lineWidth = 3.0;
        _cornerLayer.lineCap = kCALineCapRound;
        [self.layer addSublayer:_cornerLayer];
    }
    
    return self;
}


- (void)layoutSubviews {
    [super layoutSubviews];
    // 更新遮罩（外暗 + 内镂空）
    UIBezierPath *full = [UIBezierPath bezierPathWithRect:self.bounds];
    UIBezierPath *hole = [UIBezierPath bezierPathWithRoundedRect:self.scanRect cornerRadius:10];
    [full appendPath:hole];
    _maskLayer.path = full.CGPath;

    // 四角（仅角标，并非整框）
    CGFloat len = 22.0; // 角标长度
    UIBezierPath *corner = [UIBezierPath bezierPath];
    CGRect r = self.scanRect;
    // 左上
    [corner moveToPoint:CGPointMake(CGRectGetMinX(r), CGRectGetMinY(r)+len)];
    [corner addLineToPoint:CGPointMake(CGRectGetMinX(r), CGRectGetMinY(r))];
    [corner addLineToPoint:CGPointMake(CGRectGetMinX(r)+len, CGRectGetMinY(r))];
    // 右上
    [corner moveToPoint:CGPointMake(CGRectGetMaxX(r)-len, CGRectGetMinY(r))];
    [corner addLineToPoint:CGPointMake(CGRectGetMaxX(r), CGRectGetMinY(r))];
    [corner addLineToPoint:CGPointMake(CGRectGetMaxX(r), CGRectGetMinY(r)+len)];
    // 左下
    [corner moveToPoint:CGPointMake(CGRectGetMinX(r), CGRectGetMaxY(r)-len)];
    [corner addLineToPoint:CGPointMake(CGRectGetMinX(r), CGRectGetMaxY(r))];
    [corner addLineToPoint:CGPointMake(CGRectGetMinX(r)+len, CGRectGetMaxY(r))];
    // 右下
    [corner moveToPoint:CGPointMake(CGRectGetMaxX(r)-len, CGRectGetMaxY(r))];
    [corner addLineToPoint:CGPointMake(CGRectGetMaxX(r), CGRectGetMaxY(r))];
    [corner addLineToPoint:CGPointMake(CGRectGetMaxX(r), CGRectGetMaxY(r)-len)];
    _cornerLayer.path = corner.CGPath;
}


@end
